/**
 * @filename:QuotationDetailController 2021-11-09 01:40:37
 * @project com/lwl/blue  V1.0
 * Copyright(c) 2020 <a href=mailto:lanwenliang@yidianlife.com>蓝文良</a> Co. Ltd.
 * All right reserved.
 */
package com.lwl.blue.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.aliyun.openservices.shade.com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lwl.blue.commont.base.*;
import com.lwl.blue.commont.utils.EasyExcelUtils;
import com.lwl.blue.commont.utils.ParamsCheckUtilService;
import com.lwl.blue.commont.utils.UserContextUtil;
import com.lwl.blue.entity.ContractDetail;
import com.lwl.blue.entity.QuotationDetail;
import com.lwl.blue.excel.item.ItemExport;
import com.lwl.blue.excel.item.ItemImport;
import com.lwl.blue.excel.quotation.QuotationDetailExport;
import com.lwl.blue.service.FilesService;
import com.lwl.blue.service.QuotationDetailService;
import com.lwl.blue.service.QuotationService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>自定义方法写在这里</p>
 *
 * <p>说明： 报价单明细API接口层</P>
 *
 * @version: V1.0
 * @author: <a href=mailto:lanwenliang@yidianlife.com>蓝文良</a>
 */
// @Api(tags = "报价单明细" )
@RestController
@RequestMapping("/quotationDetail")
@Slf4j
public class QuotationDetailController extends BaseController {
    @Resource
    QuotationDetailService quotationDetailService;
    @Resource
    ParamsCheckUtilService paramsCheckUtil;
    @Resource
    FilesService filesService;
    @PostMapping("/pages")
    public PageResult<QuotationDetail> getPages(@RequestBody PageParam<QuotationDetail> pageParam) {
        JsonResult<Page<QuotationDetail>> pages = quotationDetailService.pages(pageParam);
        PageResult<QuotationDetail> re = new PageResult<>();
        re.success(pages.getData().getTotal(), pages.getData().getRecords());
        return re;
    }

    @PostMapping("/pagesDetail")
    public PageResult<QuotationDetail> pagesDetail(@RequestBody PageParam<QuotationDetail> pageParam) {
        PageResult<QuotationDetail> re = new PageResult<>();
        if (null == pageParam.getParam() || null == pageParam.getParam().getQuotationId()) {
            re.success(0L, new ArrayList<>());
            return re;
        }
        JsonResult<Page<QuotationDetail>> pages = quotationDetailService.pages(pageParam);
        re.success(pages.getData().getTotal(), pages.getData().getRecords());
        return re;
    }

    @PostMapping("saveOrUpdate")
    public JsonResult saveOrUpdate(@RequestBody QuotationDetail quotationDetail) {
       return  quotationDetailService.saveUpdateData(quotationDetail);
    }

    @PostMapping("/delete/{id}")
    public JsonResult saveOrUpdate(@PathVariable(value = "id") Integer id) {
        quotationDetailService.update(new UpdateWrapper<QuotationDetail>().lambda()
                .set(QuotationDetail::getIsDelete, Const.IS_DELETE_YES)
                .set(QuotationDetail::getUpdateUser, UserContextUtil.getUser().getUserName())
                .eq(QuotationDetail::getId, id));
        QuotationDetail byId = quotationDetailService.getById(id);
        filesService.updateByDelete(byId.getPhoto());
        return new JsonResult().success("请求成功");
    }

    @GetMapping("/export/{params}")
    public void export(HttpServletResponse response, @PathVariable("params") String params) throws IOException {
        QuotationDetail quotationDetail = JSON.parseObject(params, QuotationDetail.class);
        List<QuotationDetail> reList = quotationDetailService.getExportList(quotationDetail);
        List<QuotationDetailExport> quotationDetailExports = new ArrayList<>();
        if (!reList.isEmpty()) {
            reList.forEach(
                    l -> {
                        QuotationDetailExport q = new QuotationDetailExport();
                        BeanUtils.copyProperties(l, q);
                        quotationDetailExports.add(q);
                    }
            );
        }
        EasyExcelUtils.export(response, "报价单明细", ItemExport.class, quotationDetailExports);
    }

    @RequestMapping(value = "/import", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult importItem(@RequestParam("file") MultipartFile uploadFile) {
        InputStream inputStream = null;
        List<QuotationDetail> addList = new ArrayList<>();
        try {
            inputStream = uploadFile.getInputStream();
            List<QuotationDetailExport> quotationDetailExports = EasyExcelFactory.read(inputStream).sheet(0).headRowNumber(3).head(ItemImport.class).doReadSync();
            quotationDetailExports.forEach(i -> {
                QuotationDetail add = new QuotationDetail();
                paramsCheckUtil.checkObject(i);
                BeanUtils.copyProperties(i, add);
                addList.add(add);
            });
            quotationDetailService.saveOrUpdateBatch(addList);
            return new JsonResult().success("报价单明细导入成功");
        } catch (IOException e) {
            log.error("文件上传异常：{}，异常信息：{}", e, e.getMessage());
            return new JsonResult().error(e.getMessage());
        } finally {
            if (null != inputStream) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    log.error("文件上传关闭异常：{}，异常信息：{}", e, e.getMessage());
                }
            }
        }
    }
}
